package com.yjlove.myplay.ui.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yjlove.myplay.R;
import com.yjlove.myplay.base.BaseActivity;
import com.yjlove.myplay.bean.ShowImageInfo;
import com.yjlove.myplay.common.StringPath;
import com.yjlove.myplay.ui.adapter.ImagesAdapter;
import com.yjlove.myplay.ui.adapter.ImagesEditAdapter;
import com.yjlove.myplay.utils.FileAndImageUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者 YJlvoe
 * 创建时间 2017/2/23.
 */
public class GetPictureActivity extends BaseActivity implements View.OnClickListener{

    protected LayoutInflater mInflater;
    private Context mContext;

    private String mImagePath = StringPath.IMAGE_PATH;
    private SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    private static final int PICK_LOCATION_DATA = 1000;
    private static final int CAMERA_WITH_DATA = 1001;

    private GridView mGridView;
    private LinearLayout mNullLayout;
    private Button mAdd;
    private Button mDel;
    private TextView mEdit;

    private int editTag = 0;//判断是否为编辑状态
    private ImagesAdapter mImagesAdapter;// 完成时
    private ImagesEditAdapter mImagesEditAdapter;// 编辑时

    public List<Integer> mDeletePositions = new ArrayList<>();
    private List<ShowImageInfo> mImagesInfoList = new ArrayList<>();
    @Override
    protected String getActivityTitle() {
        return getIntent().getStringExtra("title");
    }

    @Override
    protected int getActivityView() {
        return R.layout.activity_picturetest;
    }

    @Override
    protected void initView() {
        mContext = getApplicationContext();
        mInflater = (LayoutInflater) (GetPictureActivity.this).getSystemService(LAYOUT_INFLATER_SERVICE);
        mGridView = (GridView) findViewById(R.id.picture_gridview);
        mNullLayout = (LinearLayout) findViewById(R.id.activity_images_null_layout);
        mEdit = (TextView) findViewById(R.id.activity_images_edit);
        mAdd = (Button) findViewById(R.id.picture_add);
        mDel = (Button) findViewById(R.id.picture_del);

    }

    @Override
    protected void initData() {
        showPhoto();
        mEdit.setOnClickListener(this);
        mAdd.setOnClickListener(this);
        mDel.setOnClickListener(this);
    }

    private void showPhoto() {
        mImagesInfoList.clear();
        mImagesInfoList = FileAndImageUtil.getImagesFullPath(mImagePath);
        if (mImagesInfoList.size() > 0) {
            mNullLayout.setVisibility(View.GONE);
            mGridView.setVisibility(View.VISIBLE);
            initGridView();
        } else {
            mNullLayout.setVisibility(View.VISIBLE);
            mGridView.setVisibility(View.GONE);
        }
    }

    private void initGridView() {

        if (editTag == 1) {
            mImagesEditAdapter = new ImagesEditAdapter(GetPictureActivity.this, mImagesInfoList);
            mImagesEditAdapter.getOnItemClickListener(new ImagesEditAdapter.ItemClickListener() {
                @Override
                public void OnItemClickListener(List<Integer> deletePositions) {
                    mDeletePositions.clear();
                    mDeletePositions.addAll(deletePositions);
                }
            });
            mGridView.setAdapter(mImagesEditAdapter);
        } else {
            mImagesAdapter = new ImagesAdapter(GetPictureActivity.this, mImagesInfoList);
            mGridView.setAdapter(mImagesAdapter);
        }
    }

    private PopupWindow mTakePhotoPopupWindow;
    private LinearLayout btn_take_photo;//拍照
    private LinearLayout btn_pick_photo;//从相册选择
    private LinearLayout pop_cancle_layout;
    // 添加图片
    private void createTakePhotoPopupWindow() {
        View newPopWindow = mInflater.inflate(R.layout.popwindow_photo, null);
        if (mTakePhotoPopupWindow != null) {
            mTakePhotoPopupWindow.dismiss();
            mTakePhotoPopupWindow = null;
        }

        mTakePhotoPopupWindow = new PopupWindow(newPopWindow, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        mTakePhotoPopupWindow.setOutsideTouchable(false);
        mTakePhotoPopupWindow.setFocusable(true);
        mTakePhotoPopupWindow.showAtLocation(findViewById(R.id.activity_images_layout), Gravity.CENTER, 0, 0);

        btn_take_photo = (LinearLayout) newPopWindow.findViewById(R.id.btn_take_photo);//拍照
        btn_pick_photo = (LinearLayout) newPopWindow.findViewById(R.id.btn_pick_photo);//从相机选择
        pop_cancle_layout = (LinearLayout) newPopWindow.findViewById(R.id.pop_cancle_layout);

        btn_take_photo.setOnClickListener(this);
        btn_pick_photo.setOnClickListener(this);
        pop_cancle_layout.setOnClickListener(this);
    }

    private File mPhotoFile;
    private void takePhotoByCapture() {
        try {
            String state = Environment.getExternalStorageState();

            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
            String curTime = formatter.format(curDate);
            String fileName = curTime + ".jpg";

            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(mImagePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                mPhotoFile = new File(mImagePath, fileName);
                if (!mPhotoFile.exists()) {
                    mPhotoFile.createNewFile();
                } else {
                    mPhotoFile.delete();
                }

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(mPhotoFile));
                startActivityForResult(intent, CAMERA_WITH_DATA);
            } else {
                Toast.makeText(getApplication(), "sdcard无效或没有插入!", Toast.LENGTH_SHORT).show();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private PopupWindow mDeletePhotoPopupWindow;
    private LinearLayout btn_delete_photo;//删除
    private LinearLayout pop_delete_cancle_layout;
    // 删除图片
    private void createDeletePhotoPopupWindow() {
        View newPopWindow = mInflater.inflate(R.layout.popwindow_photo_delete, null);
        if (mDeletePhotoPopupWindow != null) {
            mDeletePhotoPopupWindow.dismiss();
            mDeletePhotoPopupWindow = null;
        }

        mDeletePhotoPopupWindow = new PopupWindow(newPopWindow, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        mDeletePhotoPopupWindow.setOutsideTouchable(false);
        mDeletePhotoPopupWindow.setFocusable(true);
        mDeletePhotoPopupWindow.showAtLocation(findViewById(R.id.activity_images_layout), Gravity.CENTER, 0, 0);

        btn_delete_photo = (LinearLayout) newPopWindow.findViewById(R.id.btn_delete_photo);//删除
        pop_delete_cancle_layout = (LinearLayout) newPopWindow.findViewById(R.id.pop_delete_cancle_layout);

        btn_delete_photo.setOnClickListener(this);
        pop_delete_cancle_layout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (mTakePhotoPopupWindow != null) {
            mTakePhotoPopupWindow.dismiss();
            mTakePhotoPopupWindow = null;
        }
        if (mDeletePhotoPopupWindow != null) {
            mDeletePhotoPopupWindow.dismiss();
            mDeletePhotoPopupWindow = null;
        }
        switch (v.getId()){
            case R.id.activity_images_edit:
                //编辑
                if ("编辑".equals(mEdit.getText().toString())) {
                    editTag = 1;
                    mEdit.setText("完成");
                    mDel.setVisibility(View.VISIBLE);
                    mAdd.setVisibility(View.GONE);
                } else {
                    editTag = 0;
                    mEdit.setText("编辑");
                    mDel.setVisibility(View.GONE);
                    mAdd.setVisibility(View.VISIBLE);
                }
                initGridView();
                break;
            case R.id.picture_add:
                //添加
                createTakePhotoPopupWindow();
                break;
            case R.id.picture_del:
                //删除
                if (!mDeletePositions.isEmpty()){
                    createDeletePhotoPopupWindow();
                } else {
                    Toast.makeText(mContext, "未选中图片无法删除", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_take_photo:
                // 拍照
                takePhotoByCapture();
                break;
            case R.id.btn_pick_photo:
                // 打开相册
                Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(pickIntent, PICK_LOCATION_DATA);// 打开照相机
                break;
            case R.id.pop_cancle_layout:
                // 退出添加pop
                if (mTakePhotoPopupWindow != null) {
                    mTakePhotoPopupWindow.dismiss();
                    mTakePhotoPopupWindow = null;
                }
                break;
            case R.id.btn_delete_photo:
                // 删除图片
                deleteImages();
                break;
            case R.id.pop_delete_cancle_layout:
                // 退出删除pop
                if (mDeletePhotoPopupWindow != null) {
                    mDeletePhotoPopupWindow.dismiss();
                    mDeletePhotoPopupWindow = null;
                }
                break;
            default:
                break;
        }
    }
    // 删除图片
    private void deleteImages() {
        for (int position : mDeletePositions){
            FileAndImageUtil.deleteImageByName(mImagePath, mImagesInfoList.get(position).getImageName());
        }
        mDeletePositions.clear();
        showPhoto();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
        ContentResolver resolver = getContentResolver();
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String curTime = formatter.format(curDate);
        String fileName = curTime + ".jpg";
        if (resultCode != RESULT_OK) {
            if (mPhotoFile != null){
                mPhotoFile.delete();
            }
            return;
        }

        switch(requestCode){
            case CAMERA_WITH_DATA:
                break;
            case PICK_LOCATION_DATA:
                //从相册选择
                Uri selectedImage = data.getData();
                try {
                    FileAndImageUtil.copyImage(MediaStore.Images.Media.getBitmap(resolver, selectedImage), mImagePath, fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
        showPhoto();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mTakePhotoPopupWindow != null) {
                mTakePhotoPopupWindow.dismiss();
                mTakePhotoPopupWindow = null;
//            } else if (mDeletePhotoPopupWindow != null) {
//                mDeletePhotoPopupWindow.dismiss();
//                mDeletePhotoPopupWindow = null;
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
